import axios from "axios"
import Vue from "vue"
export const event = new Vue();
import {
	Message
} from "element-ui"
import cache from '@/utils/cache'
// MessageBox
// import store from '@/store';
import { getToken, setToken, removeToken } from "@/utils/auth"
import { updateToken } from "@/api/user"
import qs from "qs"
// create an axios instance
const service = axios.create({
	baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
	// withCredentials: true, // send cookies when cross-domain requests
	timeout: 15000 // request timeout
})

// axios.defaults.withCredentials = true; // 让ajax携带cookie
// request interceptor
service.interceptors.request.use(
	(config) => {
		// do something before request is sent
		if (getToken()) {
			config.headers["token"] = getToken()
		}
		// if (config.qs) {
		config.headers["Content-Type"] = "application/x-www-form-urlencoded"
		// config.headers["Content-Type"] = "multipart/form-data"
		// }
		if (config.method === "post" && config.data) {
			config.data = qs.stringify(config.data)

      const requestObj = {
        url: config.url,
        data: typeof config.data === 'object' ? qs.stringify(config.data) : config.data,
        time: new Date().getTime()
      }
      const sessionObj = cache.session.getJSON('sessionObj')
      if (sessionObj === undefined || sessionObj === null || sessionObj === '') {
        cache.session.setJSON('sessionObj', requestObj)
      } else {
        const s_url = sessionObj.url;                  // 请求地址
        const s_data = sessionObj.data;                // 请求数据
        const s_time = sessionObj.time;                // 请求时间
        const interval = 2000;                         // 间隔时间(ms)，小于此时间视为重复提交
        if (s_data === requestObj.data && requestObj.time - s_time < interval && s_url === requestObj.url) {
          const message = '数据正在处理，请勿重复提交';
          console.warn(`[${s_url}]: ` + message)
          return Promise.reject(new Error(message))
        } else {
          cache.session.setJSON('sessionObj', requestObj)
        }
      }
		}

		if (config.url.includes("upload")) {
			config.headers["Content-Type"] = "multipart/form-data"
			config.headers["token"] = getToken()
		}
		return config
	},
	(error) => {
		// do something with request error
		return Promise.reject(error)
	}
)

// response interceptor
service.interceptors.response.use(
	/**
	 * If you want to get http information such as headers or status
	 * Please return  response => response
	 */

	/**
	 * Determine the request status by custom code
	 * Here is just an example
	 * You can also judge the status by HTTP Status Code
	 */
	(response) => {
		const res = response.data

		// if the custom code is not 20000, it is judged as an error.
		if (!res.success) {
			Message({
				message: res.message || "Error",
				type: "error",
				duration: 5 * 1000
			})
		}

    let exp
    if(res.object && res.object.exp) {
      exp = res.object.exp
    } else {
      exp = window.sessionStorage.getItem("exp") || 0
    }

    // const exp = window.sessionStorage.getItem("exp")
    const timestamp = new Date().getTime()

    if ((exp - timestamp) > 0 && (exp - timestamp) < 5*60*1000) {
      // 0 - 30万毫秒
      updateToken().then(res => {
        const { object } = res
        setToken(object.token)
        sessionStorage.setItem("exp", object.exp)
        // sessionStorage.setItem("token", object.token)
      })
      return res
    } else if((exp - timestamp) < 0) {
      removeToken()
      return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
    } else {
      return res
    }
	},
	async function(error) {
    if (error.response.status == 403) {
      removeToken()
      Message({
        message: '无效的会话，或者会话已过期，请重新登录。',
        type: "warning",
        duration: 5 * 1000
      })
      location.href = '/index';
    }
		return Promise.reject(error)
	}
)

export default service
